#!/usr/bin/env python
#--*-- coding: UTF-8 --*--

import os, sys, shutil;

from CrawlerDB import CrawlerDB; # 引入数据库操作类

class PathControler:
    basePath = "/others/images/zngirls/";

    def getPathsList(self):
        print("peter");

    def moveFolder(self, srcPath, descPath, db, srcId, dbPath):
        if not os.path.exists(srcPath):
            print("The path isn't exists：%s", srcPath);
            return;

        name = srcPath.rpartition("/")[2];

        if not os.path.exists(descPath + name):
            shutil.move(srcPath, destPath);
            db.savePagePath(srcId, dbPath);
            return;

        list = os.listdir(srcPath);
        descPath = descPath + name + "/";

        for path in list:
            srcFile = srcPath + "/" + path;
            descFile = descPath + path;

            if os.path.exists(descFile):
                os.remove(descFile);

            shutil.move(srcFile, descPath);
            db.savePagePath(srcId, dbPath);

        os.remove(srcPath);

    def main(self):
        index = 43;
        # endId = 3790;
        endId = 50;
        db = CrawlerDB();

        try:
            while(index < endId):
                dbPath = "g" + str(index).zfill(3);
                destPath = self.basePath + dbPath + "/";
                srcId = (index - 1) * 100 + 1;
                print("The current id is %d" % (index));
                sys.stdout.flush();

                if not os.path.exists(destPath):
                    os.makedirs(destPath);

                while(srcId < index * 100 + 1):
                    srcPath = self.basePath + str(srcId).zfill(5);
                    self.moveFolder(srcPath, destPath, db, srcId, dbPath);
                    srcId += 1;

                index += 1;
        finally:
            db.close();

    def test(self):
        list = os.listdir("/others/images/zngirls/04273");
        print(list);

def test():
    PathControler().main();
    # PathControler().moveFolder("/others/images/zngirls/04273", "/others/images/zngirls/g043");
    # PathControler().test();

test();
